package com.ruoyi.app.controller;


import cn.hutool.core.util.IdUtil;
import com.ruoyi.app.domain.MemberUser;
import com.ruoyi.app.domain.OperStaff;
import com.ruoyi.app.service.IMemberUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.jwt.JwtHelper;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.vo.MemberUserVo;
import com.ruoyi.common.vo.OnlineUserList;
import com.ruoyi.framework.websocket.WebSocketServer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/app/login/")
public class ApiLoginController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IMemberUserService memberUserService;

    private static Map<String, String> LOGINUSERS = new ConcurrentHashMap<String, String>();
    @Value("${spring.passwordSalt}")
    private String passwordSalt;

    @Anonymous
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody MemberUser member) {

        Map<String, Object> result = new HashMap<String, Object>();

        OperStaff operStaff = memberUserService.checkLogin(member.getUsername());
        if(operStaff == null){
            return error("帐号或密码错误");
        }
        LOGGER.error("\n 登录帐号- {}", member.getUsername());
//        if (OnlineUserList.checkUser(member.getUsername())) {
//            // 用户已登录，可以继续处理请求
//            return error("该帐号已经登录,请联系管理员");
//        }
        if(!Md5Utils.hash(passwordSalt + member.getPassword()).equals(operStaff.getPassword())){
            return error("帐号或密码错误");
        }
        LOGGER.error("\n 登录成功帐号- {}", member.getUsername());
        String jwtToken = JwtHelper.generateToken(operStaff.getLoginName(), String.valueOf(operStaff.getId()));

        Map<String,Object> map = new HashMap<String,Object>();

        LOGINUSERS.put("userId",String.valueOf(operStaff.getId()));
        OnlineUserList.addUser(member.getUsername());

        map.put("id",operStaff.getId());
        map.put("staffName",operStaff.getStaffName());
        map.put("staffGroupName",operStaff.getStaffGroupName());
        map.put("duty",operStaff.getDuty());
        map.put("dutyType",operStaff.getDutyType());
        map.put("accessToken",jwtToken);
        return AjaxResult.success("成功",map);
    }
    @Anonymous
    @GetMapping ("/getuser")
    @ResponseBody
    public AjaxResult getuser() {

        List<String> userList = OnlineUserList.getUserList();

        return AjaxResult.success("成功",userList);
    }
    @Anonymous
    @PostMapping("/forget")
    @ResponseBody
    public AjaxResult forget(@RequestBody MemberUserVo member) {

        Map<String, Object> result = new HashMap<String, Object>();

        MemberUser memberUser = memberUserService.checkEmailIsRegister(member.getEmail());
        if(memberUser == null){
            return error("邮箱未注册");
        }
        String sessMobileCode = redisUtils.get(member.getEmail()+"_register");
        if (!member.getMobileCode().equals(sessMobileCode)) {
            return error("验证码不正确");
        }
        // 登录成功后的公共逻辑
        // 更新用户最近登录时间
        MemberUser memberCom = new MemberUser();
        memberCom.setId(memberUser.getId());
        member.setPassword(SecurityUtils.encryptPassword(member.getPassword()));
        memberUserService.updateMemberUser(memberCom);

        return AjaxResult.success("修改成功",result);
    }
}
